<template>
  <div class="content">
    <!-- 用户填写身份信息 -->
    <el-dialog
      v-model="agencyLogin"
      title="信息填写"
      :before-close="close"
    >
      <el-card>
        <!-- 账号信息填写框 -->
        <div v-show="active2">
          <el-form
            ref="ruleFormRef1"
            :model="ruleForm1"
            status-icon
            :rules="rules1"
            label-width="auto"
          >
            <el-form-item label="账号" prop="account">
              <el-input v-model="ruleForm1.account" />
            </el-form-item>
            <el-form-item label="密码" prop="pass">
              <el-input
                v-model="ruleForm1.pass"
                type="password"
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPass">
              <el-input
                v-model="ruleForm1.checkPass"
                type="password"
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="submitForm1(ruleFormRef1)"
                style="margin-left: 100px"
              >
                {{ submitText1 }}
              </el-button>
              <el-button @click="resetForm1(ruleFormRef1)">重置</el-button>
              <el-button @click="nextStep">上一步</el-button>
            </el-form-item>
          </el-form>
        </div>
        <!-- 基本信息填写框 -->
        <div v-show="active1">
          <el-form
            ref="ruleFormRef2"
            :model="ruleForm2"
            status-icon
            :rules="rules2"
            label-width="auto"
          >
            <el-form-item label="学校" prop="sch">
              <el-input v-model="ruleForm2.sch" />
            </el-form-item>
            <el-form-item label="年级" prop="sgrade">
              <el-input v-model="ruleForm2.sgrade" />
            </el-form-item>
            <el-form-item label="姓名" prop="sname">
              <el-input v-model="ruleForm2.sname" />
            </el-form-item>
            <el-form-item label="年龄" prop="age">
              <el-input v-model.number="ruleForm2.age" />
            </el-form-item>
            <el-form-item style="margin-left: 100px">
              <el-button type="primary" @click="submitForm2(ruleFormRef2)">
                {{ submitText2 }}
              </el-button>
              <el-button @click="resetForm2(ruleFormRef2)">重置</el-button>
              <el-button @click="nextStep">下一步</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>

      <el-steps
        style="width: 100%"
        :active="active"
        finish-status="success"
        mt-20px
      >
        <el-step title="基本信息" />
        <el-step title="账号信息" />
      </el-steps>
    </el-dialog>
    <!-- 身份确认框 -->
    <el-dialog
      v-model="dialogVisible"
      title="身份验证"
      :before-close="handleClose"
    >
      <span>请在测试前核对您的身份信息</span>
      <el-card m-t15px shadow="hover">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        <p font-size="15px">学校：{{ ruleForm2.sch }}</p>
        <p font-size="15px" m-t10px>年级：{{ ruleForm2.sgrade }}</p>
        <p font-size="15px" m-t10px>姓名：{{ ruleForm2.sname }}</p>
        <p font-size="15px" m-t10px>年龄：{{ ruleForm2.age }}</p>
      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">有问题,报告老师</el-button>
          <el-button type="primary" @click="testBegin">
            确认无误,去测试
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-card class="c1">
      <!-- 问卷标题 -->
      <template #header>
        <div
          class="card-header"
          style="
            display: flex;
            align-items: center;
            justify-content: space-between;
          "
        >
          <div>
            <svg
              @click="goBack"
              t="1721642273271"
              class="icon"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="4043"
            >
              <path
                d="M648 307.2H217.6l128-128c12.8-12.8 12.8-32 0-44.8-12.8-12.8-32-12.8-44.8 0L118.4 315.2c-6.4 6.4-9.6 14.4-9.6 22.4s3.2 16 9.6 22.4l180.8 180.8c12.8 12.8 32 12.8 44.8 0 12.8-12.8 12.8-32 0-44.8l-124.8-124.8h428.8c120 0 216 96 216 216s-96 216-216 216H320c-17.6 0-32 14.4-32 32s14.4 32 32 32h328c155.2 0 280-124.8 280-280s-124.8-280-280-280z"
                p-id="4044"
              ></path>
            </svg>
            <span
              m-l5px
              style="font-size: 20px; font-weight: 550; line-height: 32px"
              >{{ testMessage.testName }}</span
            >
          </div>
          <el-button
            type="info"
            v-show="!getInfo2 || show1 == true"
            plain
            round
            large
            @click="agencyLogin = true"
            >我的信息</el-button
          >
        </div>
      </template>

      <!-- 上一题、下一题 -->
      <div class="progress">
        <div>
          <el-button @click="goLast" :disabled="sid == 0 ? true : false"
            >上一题</el-button
          >
          <el-button
            @click="goNext"
            :disabled="
              sid >= testMessage.cnt - 1 || start == false ? true : false
            "
            >下一题</el-button
          >
        </div>
        <el-button
          @click="commit"
          v-show="flag === testMessage.cnt ? true : false"
          style="
            width: 90px;
            /* background: radial-gradient(
              circle at 10% 20%,
              #fffcd6 0%,
              #fdece0 90%
            ); */
          "
        >
          提交
        </el-button>
      </div>

      <!-- 进度条 -->
      <el-progress
        :percentage="
          show1 == true
            ? 100 * ((sid + 0.05) / testMessage.cnt)
            : 100 * ((sid + 1) / testMessage.cnt)
        "
        color="#2c9caf"
      >
        <el-button text font-size="16px" color="#fff"
          >{{ show1 == true ? sid : sid + 1 }}/{{ testMessage.cnt }}</el-button
        >
      </el-progress>

      <!-- 测评须知 -->
      <el-card class="c2" v-show="show1">
        <div m-b40px font="bold" font-size="18px">测评须知:</div>
        <div v-for="item in testMessage.testNotice" m-b20px>{{ item }}</div>
        <div class="elbutton">
          <el-button
            type="danger"
            w-500px
            m-t20px
            font-size="16px"
            round
            @click="goTest"
            >知道了，去测试</el-button
          >
        </div>
      </el-card>

      <!-- 答题卡片组 -->
      <transition-group name="card" style="">
        <el-card class="c3" v-show="show2">
          <div font-bold font-size="18px" color="#000">
            第{{ testMessage.testOptions[sid].key }}题:
            {{ testMessage.testOptions[sid]?.title }}
          </div>

          <div class="c4">
            <div
              v-for="(item, index) in testMessage.testOptions[sid].selection"
              :key="index"
            >
              <el-button
                :class="{
                  option: true,
                  active: testMessage.testOptions[sid].selectedOne === index,
                }"
                @click="select(index)"
              >
                {{ item }}
              </el-button>
            </div>
          </div>
        </el-card>
      </transition-group>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue'
import type { FormInstance, FormRules, Action } from 'element-plus'
import { h } from 'vue'
import { ElNotification } from 'element-plus'
import usePsyExamStore from '../../../store/psy/psyExam'
const user = ref({
  account: '1234567',
  pwd: '123',
  sch: 'XX学校',
  sgrade: '初一',
  age: 16,
  sname: '白光莹',
})

const agencyLogin = ref(true)
const active = ref(0)
const active1 = ref(true)
const active2 = ref(false)
const getInfo1 = ref(false)
const getInfo2 = ref(false)
const submitText1 = ref('提交')
const submitText2 = ref('提交')

const dialogVisible = ref(false)
/**
 * 当前题号
 */
const sid = ref(0)
const show1 = ref(true)
const show2 = ref(false)
const start = ref(false)
const flag = ref(0)
const sumScore = ref(0)

// 关闭信息填写框
const close = (done: () => void) => {
  ElMessageBox.confirm('是否关闭信息填写框？')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}

//退出测评须知页
const goBack = () => {}

//填写信息步骤条
const nextStep = () => {
  active1.value = !active1.value
  active2.value = !active2.value
  if (active.value++ > 1) active.value = 0
}

interface RuleForm1 {
  account: string
  pass: string
  checkPass: string
}
interface RuleForm2 {
  sch: string
  sgrade: string
  sname: string
  age: number
}

const ruleFormRef1 = ref<FormInstance>()
const ruleFormRef2 = ref<FormInstance>()

//表单校验
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('密码不为空'))
  } else {
    if (ruleForm1.checkPass !== '') {
      if (!ruleFormRef1.value) return
      ruleFormRef1.value.validateField('checkPass')
    }
    callback()
  }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== ruleForm1.pass) {
    callback(new Error('两次密码不一致!'))
  } else {
    callback()
  }
}
const validateSch = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入学校名称'))
  } else {
    callback()
  }
}
const validateSgrade = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入年级'))
  } else {
    callback()
  }
}
const validateSname = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入姓名'))
  } else {
    callback()
  }
}
const checkAge = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入年龄'))
  }
  setTimeout(() => {
    if (!Number.isInteger(value)) {
      callback(new Error('请输入数字'))
    } else {
      if (value < 5) {
        callback(new Error('年龄必须大于5'))
      } else {
        callback()
      }
    }
  }, 1000)
}

const ruleForm1 = reactive<RuleForm1>({
  account: '',
  pass: '',
  checkPass: '',
})

const ruleForm2 = reactive<RuleForm2>({
  sch: '',
  sgrade: '',
  sname: '',
  age: '',
})

const rules1 = reactive<FormRules<typeof ruleForm1>>({
  account: [
    { required: true, message: '请输入正确的用户账号', trigger: 'blur' },
    { min: 6, max: 10, message: '账号长度须在6到10之间', trigger: 'blur' },
  ],
  pass: [{ required: true, validator: validatePass, trigger: 'blur' }],
  checkPass: [{ required: true, validator: validatePass2, trigger: 'blur' }],
})

const rules2 = reactive<FormRules<typeof ruleForm2>>({
  sch: [{ validator: validateSch, trigger: 'blur' }],
  sgrade: [{ validator: validateSgrade, trigger: 'blur' }],
  sname: [{ validator: validateSname, trigger: 'blur' }],
  age: [{ validator: checkAge, trigger: 'blur' }],
})
//重置和确认按钮
const submitForm1 = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (
      ruleForm1.pass == user.value.pwd &&
      ruleForm1.account == user.value.account &&
      valid === true
    ) {
      ElNotification({
        title: '账号信息验证',
        message: h('i', { style: 'color: teal' }, '验证成功'),
      })
      submitText1.value = '已验证'
      agencyLogin.value = false
      getInfo1.value = true
    } else {
      console.log(valid)
      ElNotification({
        title: '账号信息验证',
        message: h('i', { style: 'color: teal' }, '验证失败'),
      })
    }
  })
}

const submitForm2 = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (
      ruleForm2.sch == user.value.sch &&
      ruleForm2.sgrade == user.value.sgrade &&
      ruleForm2.sname == user.value.sname &&
      ruleForm2.age == user.value.age &&
      valid === true
    ) {
      ElNotification({
        title: '基本信息验证',
        message: h('i', { style: 'color: teal' }, '验证成功'),
      })
      submitText2.value = '已验证'
      getInfo2.value = true
    } else {
      console.log(valid)
      ElNotification({
        title: '基本信息验证',
        message: h('i', { style: 'color: teal' }, '验证失败'),
      })
    }
  })
}

const resetForm1 = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  getInfo1.value = false
  submitText1.value = '提交'
}
const resetForm2 = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  getInfo2.value = false
  submitText2.value = '提交'
}

const testBegin = () => {
  if (getInfo1.value === true && getInfo2.value === true) {
    show1.value = false
    show2.value = true
    start.value = true
    dialogVisible.value = false
  } else {
    ElMessageBox.alert('请先完成信息填写再进行测试', '温馨提示', {
      // if you want to disable its autofocus
      // autofocus: false,
      confirmButtonText: '好的',
      callback: (action: Action) => {
        ElMessage({
          type: 'info',
          message: `信息核对失败`,
        })
      },
    })
  }
}

// 关闭信息确认框
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('确认退出信息核对？')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}

const examStore = usePsyExamStore()
const testMessage = examStore.examInfo

const goTest = () => {
  dialogVisible.value = true
}

const goLast = () => {
  sid.value -= 1
}
const goNext = () => {
  if (sid.value < testMessage.cnt - 1) {
    sid.value += 1
  } else {
    sid.value = testMessage.cnt - 1
  }
}

const select = (key) => {
  if (testMessage.testOptions[sid.value].selectedOne === -1) {
    flag.value += 1
  } else {
    sumScore.value -=
      testMessage.testOptions[sid.value].score[
        testMessage.testOptions[sid.value].selectedOne
      ]
  }
  testMessage.testOptions[sid.value].selectedOne = key
  sumScore.value += testMessage.testOptions[sid.value].score[key]
  setTimeout(() => {
    goNext()
  }, 200)
}

const commit = () => {
  if (flag.value >= testMessage.cnt) {
    ElMessageBox.confirm('是否提交并完成本次测评?', '确认', {
      confirmButtonText: '确定',
      cancelButtonText: '再看看',
      type: 'warning',
    })
      .then(() => {
        ElMessage({
          type: 'success',
          message: '提交成功',
        })
        agencyLogin.value = true
        active1.value = true
        active2.value = false
        //重置账号信息
        ruleFormRef1.value?.resetFields()
        ruleFormRef2.value?.resetFields()
        getInfo1.value = false
        submitText1.value = '提交'
        getInfo2.value = false
        submitText2.value = '提交'
        // 重置答题记录
        show1.value = true
        show2.value = false
        start.value = false
        sid.value = 0
        flag.value = 0
        sumScore.value = 0
        for (var i = 0; i < testMessage.cnt; i++) {
          testMessage.testOptions[i].selectedOne = -1
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消提交',
        })
      })
  }
  if (sid.value === testMessage.cnt && flag.value < testMessage.cnt) {
    ElMessageBox.alert('还有题目未完成，请继续作答', '题目未完成', {
      // if you want to disable its autofocus
      // autofocus: false,
      confirmButtonText: '好的',
      callback: (action) => {
        ElMessage({
          type: 'info',
          message: `action: ${action}`,
        })
      },
    })
  }
}
</script>

<script lang="ts">
/**
 * 量表测试页
 * 负责人：谭烨
 */
export default {
  name: 'TableTest',
}
</script>

<style scoped>
.content {
  height: 100vh;
  width: 100%;
  .c1 {
    .icon {
      font-weight: 850;
      width: 20px;
      height: 20px;
      color: black;
      cursor: pointer;
    }
    background: url('@/views/psy/home/images/homebg1.png');
    background-repeat: no-repeat;
    background-size: cover;
    height: 100%;
    .progress {
      display: flex;
      justify-content: space-between;
      .el-button {
        color: black;
        border: 1.5px solid #1ebbef;
        font-size: 14px;
        border-radius: 6px;
        height: 2.8em;
        line-height: 2.8em;
      }
    }

    .c2 {
      height: 280px;
      opacity: 0.85;

      .elbutton {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 3em;
        line-height: 4em;
      }
    }

    .c3 {
      opacity: 0.85;
      height: 430px;
      margin-top: 8px;
      border-radius: 20px;

      .c4 {
        /* display: flex; */
        /* flex-wrap: wrap; */
        /* align-content: space-between; */
        /* margin-top: 50px; */
        .option {
          width: 80%;
          margin-top: 35px;
          margin-left: 10%;
          padding: 12px;
          font-family: inherit;
          font-size: 16px;
          height: 2.8em;
          line-height: 2.8em;
          border-radius: 4px;
          box-shadow: 2px 2px 7px 0 rgb(0, 0, 0, 0.2);
          border: 2px solid #1ebbef;
          color: rgb(0, 0, 0);
        }
      }

      .active {
        color: white;
        background-color: rgb(139, 232, 201);
        opacity: 100;
      }
    }
  }
}
</style>
<style>
.el-message-box {
  top:-15%;
  left:10%;
  width: 300px;
}
.el-overlay-dialog {
  left: 18%;
  width:80%;
  top:5%;
}
</style>
